package com.xuecheng.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.StudySystemException;
import com.xuecheng.search.po.CourseIndex;
import com.xuecheng.search.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @description 课程索引管理接口实现
 * @author Mr.M
 * @date 2022/9/25 7:23
 * @version 1.0
 */
@Slf4j
@Service
public class IndexServiceImpl implements IndexService {
    private final RestHighLevelClient client;
    public IndexServiceImpl(RestHighLevelClient client) {
        this.client = client;
    }

    @Override
    public Boolean addCourseIndex(String esIndex,String esType, CourseIndex object) {
        String json = JSON.toJSONString(object);
        IndexRequest request = new IndexRequest(esIndex, esType,
                object.getId().toString());
        request.source(json, XContentType.JSON);
        //索引响应对象
        IndexResponse indexResponse = null;
        try {
            indexResponse = client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("添加索引出错:{}",e.getMessage());
            e.printStackTrace();
            StudySystemException.cast("添加索引出错");
        }
        String name = indexResponse.getResult().name();
        System.out.println(name);
        return name.equalsIgnoreCase("created") || name.equalsIgnoreCase("updated");

    }

    @Override
    public Boolean updateCourseIndex(String esIndex,String esType, CourseIndex object) {
        String jsonString = JSON.toJSONString(object);
        UpdateRequest updateRequest = new UpdateRequest(esIndex, esType, object.getId().toString());
        updateRequest.doc(jsonString, XContentType.JSON);
        UpdateResponse updateResponse = null;
        try {
            updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("更新索引出错:{}",e.getMessage());
            e.printStackTrace();
            StudySystemException.cast("更新索引出错");
        }
        DocWriteResponse.Result result = updateResponse.getResult();
        return result.name().equalsIgnoreCase("updated");

    }
}
